import $utils from '@/plugins/utils'
import api from '@/plugins/http/api'
import mainMixin from '@/plugins/mixin'
import store from '@/store'
import { whitePages } from '@/plugins/http/whitePages'

let requestTask = null

const http = opt => {
    opt = opt || {};
    opt.timeout = opt.timeout || (1000 * 10);
    opt.data = opt.data || {};
    opt.header = opt.header || {};
    opt.method = opt.method ? opt.method.toUpperCase() : 'POST';
    return new Promise((resolve, reject) => {
        http.beforeHttp(opt).then(opt => {
            opt.header.loading = opt.header.loading || {}
            if (opt.header.loading.show == undefined) opt.header.loading.show = true
            if (opt.header.loading.show) uni.showLoading({
                title: opt.header.loading.title || '拼命加载中...',
                mask: opt.header.loading.mask || true
            })
            requestTask = uni.request({
                url: opt.url,
                method: opt.method,
                data: opt.data,
                header: opt.header,
                dataType: opt.dataType || 'JSON',
                timeout: opt.timeout,
                // #ifdef H5 
                withCredentials: true,
                // #endif
                // responseType:opt.responseType,
                success(result) {
                    http.afterHttp(result).then(res => {
                        if (opt.header.loading.show) uni.hideLoading()
                        if (res.returnCode == 0) {
                            resolve(res)
                        } else {
                            reject(res)
                        }
                    }).catch(err => {
                        uni.showToast({
                            icon: 'none',
                            duration: 2000,
                            title: err.msg || '请求失败',
                        });
                        reject(err)
                    })
                },
                fail(err) {
                    uni.showToast({
                        icon: 'none',
                        duration: 2000,
                        title: err || '请求失败'
                    })
                    reject(err)
                },
                complete(res) {
                    if (requestTask) {
                        requestTask.abort()
                    }
                    if (opt.header.loading.show) uni.hideLoading()
                }
            })
        }).catch(err => {
            uni.showToast({
                icon: 'none',
                duration: 2000,
                title: err || '请求失败',
            });
            reject(err)
        })
    })
}


http.beforeHttp = config => {
    return new Promise((resolve, reject) => {
        const page = $utils.getCurPage().route;
        let userInfo = store.state?.userInfo || {};
        if (config.method == 'POST') {
            config.header = Object.assign({
                'content-type': 'application/json'
            }, config.header)
        }
        config.data = {
            ...Object.assign(config.data, userInfo)
        };
        if (whitePages.includes(page)) {
            resolve(config)
        } else {
            if (userInfo.token) {
                resolve(config)
            } else {
                reject('登录失效，请重新登录')
                uni.reLaunch({
                    url: `/pages/login/index?redirect=${page}`
                });
            }
        }
    })
}

http.afterHttp = res => {
    return new Promise((resolve, reject) => {
        const httpSuccess = res.data && (Number(res.statusCode) >= 200 && Number(res.statusCode) < 400)
        if (httpSuccess) {
            const rs = res.data ? JSON.parse(res.data) : {};
            resolve(rs)
        } else {
            reject(res.data)
        }
    })
}


http.install = Vue => {
    Vue.mixin(mainMixin)
    Vue.prototype.$http = http
    Vue.prototype.$api = api
    Vue.prototype.$utils = $utils
}


export default http
